# -*- coding: utf-8 -*-
"""
@Author：mengying
@file： views.py
@date：2023/12/19 17:53
@email: 652044581@qq.com
@desc: 
"""
from sanic.views import HTTPMethodView
from sanic.response import json as JsonResponse
from utils.myResFormat import ResultJson, ResultCode
from utils.myEncrypt import HashCipher
from utils.myTimeFormat import MyTime
from utils.myCache import RedisAsyncTool
from utils.myDataUtils import TreeBuilder
from api.login.captchaImage import CaptchaImage
from addict import Dict
from aredis import StrictRedis
from config import config
from database.model.dept import SystemDeptDao, SystemDelEnum, SystemStatusEnum
from database.model.role import SystemRoleDao, SystemRoleMenuDao
from database.model.menu import SystemMenuDao
from database.model.mobileUser import MobileUserDao
import uuid
import itertools
import json



class RegisterView(HTTPMethodView):
    async def post(self, request):
        """【系统注册】注册"""
        # request 参数属性接口, args, json, form 
        data: Dict = request.json
        # 手机号和密码
        username = data.get("username", "")
        pwd = data.get("password", "")
        # 查询 是否存在
        user_data = await MobileUserDao().find_one(condition=dict(username=username))
        if not user_data:
            # 用户不存在,开始创建
            new_user = {
                "username": username,
                "password": HashCipher.md5(config.ENCRYPT_STRING + str(pwd))
            }
            isSuccess = await MobileUserDao().insert_one(data=new_user)
            if isSuccess:
                return JsonResponse(ResultJson(ResultCode.SUCCESS,).result)
            else:
                return JsonResponse(ResultJson(ResultCode.FAIL).result)
        else:
            return JsonResponse(ResultJson(ResultCode.USER_ERROR).result)

        


class LoginView(HTTPMethodView):

    async def post(self, request):
        """【系统登陆】登陆"""
        data: Dict = request.json

        # 验证码账号密码
        username = data.get("username", "")
        password = data.get("password", "")

        condition = {
            "username": username,
            "password": HashCipher.md5(config.ENCRYPT_STRING + str(password))
        }
       
        user_data = await MobileUserDao().find_one(condition=condition)
        print('用户登录信息: {}'.format(user_data))
        
        if not user_data:
            return JsonResponse(ResultJson(ResultCode.PASSWORD_ERROR).result)
        else:
            # 用户是否被删除
            delFlag = user_data.get("delFlag")
            if delFlag == SystemDelEnum.p1.value:
                return JsonResponse(ResultJson(ResultCode.USER_NOT_EXIST).result)

            # 用户是否被禁用
            status = user_data.get("status")
            if status == SystemStatusEnum.p1.value:
                return JsonResponse(ResultJson(ResultCode.USER_NOT_ALLOW).result)

            # 获取token信息
            token = uuid.uuid4().hex
            # 移除 password
            user_data.pop('password')
            userInfo = Dict()
            userInfo.token = token
            userInfo.user = user_data

            # 更新 redis 用户信息
            await RedisAsyncTool().set(token, json.dumps(userInfo.to_dict()), 60 * 60)
                        
            return JsonResponse(ResultJson(ResultCode.SUCCESS, data=userInfo.to_dict()).result)

class LogoutView(HTTPMethodView):

    async def post(self, request):
        """【系统登陆】退出登录"""
        token = request.headers.user_info.get("token")

        # 删除token
        if await RedisAsyncTool().get(token):
           await RedisAsyncTool().delete(token)

        return JsonResponse(ResultJson(ResultCode.SUCCESS).result)


class GetInfoView(HTTPMethodView):

    async def get(self, request):
        """【系统登陆】获取登陆用户信息"""
        mobile_user_info = request.headers.mobile_user_info
        return JsonResponse(ResultJson(ResultCode.SUCCESS, data=mobile_user_info).result)
